
import struct
import cPickle

def pack_string(astring):
    """
    not using "p" format, because it has a length limitation (can only hold 255 characters at maximum)
    """
    str_len = len(astring)
    serial_format= "=I"+str(str_len) +"s"
    return struct.pack(serial_format,str_len,astring)

def unpack_string(binimage,offset):
    # -------------- first parse out length of the string
    serial_format = "=I"
    size = struct.calcsize(serial_format)
    str_len, = struct.unpack(serial_format,binimage[offset : offset + size])
    
    # -------------- second parse out string itself
    offset += size
    serial_format = "="+str(str_len) +"s"
    size = struct.calcsize(serial_format)
    astring, = struct.unpack(serial_format,binimage[offset : offset + size]) 
    
    return (astring,offset+size)

class CPickleSerializer(object):
    @staticmethod
    def serialize(obj):
        return cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL)
    
    @staticmethod
    def deserialize(binimage):
        return cPickle.loads(binimage)
    
    
    